<template>
  <div class="file-upload">
    <el-card>
      <template #header>
        <div class="upload-header">
          <span class="upload-title">
            <el-icon><Upload /></el-icon>
            Excel/CSV文件导入
          </span>
          <el-button size="small" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载模板
          </el-button>
        </div>
      </template>

      <!-- 文件上传区域 -->
      <el-upload
        ref="uploadRef"
        class="upload-dragger"
        drag
        :auto-upload="false"
        :multiple="false"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        accept=".xlsx,.xls,.csv"
      >
        <div class="upload-content">
          <el-icon class="upload-icon" size="67">
            <component :is="uploadStatus === 'uploading' ? 'Loading' : 'UploadFilled'" />
          </el-icon>
          
          <div class="upload-text">
            <p v-if="uploadStatus === 'ready'">
              将文件拖到此处，或<em>点击选择文件</em>
            </p>
            <p v-else-if="uploadStatus === 'uploading'">
              正在上传文件... {{ uploadProgress }}%
            </p>
            <p v-else-if="uploadStatus === 'success'">
              文件上传成功！
            </p>
            <p v-else-if="uploadStatus === 'error'">
              文件上传失败，请重试
            </p>
          </div>
          
          <div class="upload-hint">
            <p>支持格式：.xlsx, .xls, .csv（最大10MB）</p>
            <p>支持字段自动识别（如"建筑ID"、"id"、"建筑编号"均视为ID字段）</p>
          </div>
        </div>
      </el-upload>

      <!-- 选中文件信息 -->
      <div v-if="selectedFile" class="selected-file">
        <div class="file-info">
          <span>{{ selectedFile.name }}</span>
          <span>{{ formatFileSize(selectedFile.size) }}</span>
        </div>
        <el-progress 
          :percentage="uploadProgress" 
          :stroke-width="6"
          :status="uploadStatus === 'error' ? 'exception' : (uploadStatus === 'success' ? 'success' : 'active')"
          class="upload-progress"
        />
        <div class="file-actions">
          <el-button type="primary" @click="uploadFile" :loading="uploadStatus === 'uploading'">
            <el-icon><RefreshLeft /></el-icon>
            开始导入
          </el-button>
          <el-button type="text" @click="clearFile">
            <el-icon><Delete /></el-icon>
            取消
          </el-button>
        </div>
      </div>

      <!-- 导入结果 -->
      <div v-if="importResult" class="import-result">
        <el-alert
          :title="getResultTitle()"
          :type="getResultType()"
          :closable="false"
          show-icon
          class="result-alert"
        >
          <template #default>
            <div class="result-details">
              <div class="result-stats">
                <el-statistic title="总记录数" :value="importResult.totalRows || 0" />
                <el-statistic title="成功导入" :value="importResult.successCount || 0" />
                <el-statistic title="导入失败" :value="importResult.errorCount || 0" />
              </div>
              
              <!-- 错误详情（最多显示前10条） -->
              <div v-if="importResult.errors && importResult.errors.length > 0" class="error-details">
                <h4>错误详情 (前{{ Math.min(importResult.errors.length, 10) }}条):</h4>
                <el-scrollbar height="200px">
                  <div
                    v-for="(error, index) in importResult.errors.slice(0, 10)"
                    :key="index"
                    class="error-item"
                  >
                    <el-tag type="danger" size="small">第 {{ error.row }} 行</el-tag>
                    <span class="error-message">{{ error.error }}</span>
                  </div>
                </el-scrollbar>
              </div>
            </div>
          </template>
        </el-alert>
        
        <div class="result-actions">
          <el-button @click="resetUpload">
            <el-icon><Refresh /></el-icon>
            继续导入
          </el-button>
          <el-button type="success" @click="$emit('refresh')">
            <el-icon><Document /></el-icon>
            查看数据
          </el-button>
        </div>
      </div>

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Upload, Download, UploadFilled, Loading, 
  RefreshLeft, Refresh, Document, Delete 
} from '@element-plus/icons-vue'
import { apiService } from '../api'

const emit = defineEmits(['success', 'refresh'])

const uploadRef = ref()
const uploadStatus = ref('ready') // ready, uploading, success, error
const uploadProgress = ref(0)
const importResult = ref(null)
const templateInfo = ref(null)
const selectedFile = ref(null)

// 文件选择处理
const handleFileChange = (file) => {
  selectedFile.value = file.raw
  uploadStatus.value = 'ready'
  importResult.value = null
}

// 上传前检查
const beforeUpload = (file) => {
  const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                      'application/vnd.ms-excel', 
                      'text/csv'].includes(file.type) ||
                     ['.xlsx', '.xls', '.csv'].some(ext => file.name.toLowerCase().endsWith(ext))
  
  const isLt10M = file.size / 1024 / 1024 < 10
  
  if (!isValidType) {
    ElMessage.error('只能上传 Excel 或 CSV 文件！')
    return false
  }
  
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB！')
    return false
  }
  
  return false // 阻止默认上传，手动控制
}

// 手动上传文件
const uploadFile = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  uploadStatus.value = 'uploading'
  uploadProgress.value = 0
  
  try {
    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += Math.random() * 30
      }
    }, 200)
    
    const response = await apiService.importExcel(selectedFile.value)
    
    clearInterval(progressInterval)
    uploadProgress.value = 100
    uploadStatus.value = 'success'
    importResult.value = response
    
    if (response.successCount > 0) {
      ElMessage.success(`成功导入 ${response.successCount} 条记录`)
      emit('success', response)
    } else {
      ElMessage.warning('没有成功导入任何记录，请检查数据格式')
    }
  } catch (error) {
    console.error('上传失败:', error)
    uploadStatus.value = 'error'
    uploadProgress.value = 0
    importResult.value = null
    
    // 错误类型细分
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('上传超时，请检查网络连接或稍后再试')
    } else if (error.response?.status === 413) {
      ElMessage.error('文件过大，请选择较小的文件')
    } else if (error.response?.status === 400) {
      ElMessage.error(`格式错误: ${error.response.data.message || '数据不符合要求'}`)
    } else {
      ElMessage.error('文件上传失败，请检查网络连接后重试')
    }
  }
}

// 清除文件选择
const clearFile = () => {
  selectedFile.value = null
  uploadStatus.value = 'ready'
  uploadProgress.value = 0
  importResult.value = null
  uploadRef.value?.clearFiles()
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取结果标题
const getResultTitle = () => {
  if (!importResult.value) return ''
  
  const { successCount, errorCount, totalRows } = importResult.value
  
  if (errorCount === 0) {
    return `导入完成 - 全部 ${totalRows} 条记录导入成功`
  } else if (successCount === 0) {
    return `导入失败 - 全部 ${totalRows} 条记录导入失败`
  } else {
    return `部分导入成功 - ${successCount}/${totalRows} 条记录导入成功`
  }
}

// 获取结果类型
const getResultType = () => {
  if (!importResult.value) return 'info'
  
  const { successCount, errorCount } = importResult.value
  
  if (errorCount === 0) return 'success'
  if (successCount === 0) return 'error'
  return 'warning'
}

// 重置上传
const resetUpload = () => {
  uploadStatus.value = 'ready'
  uploadProgress.value = 0
  importResult.value = null
  selectedFile.value = null
  uploadRef.value?.clearFiles()
}

// 下载模板
const downloadTemplate = async () => {
  try {
    // 增加加载状态提示
    ElMessage.info('正在准备模板，请稍候...')
    
    const data = await apiService.getImportTemplate()
    
    // 验证接口返回数据格式
    if (!data || (!data.requiredFields && !data.exampleData)) {
      throw new Error('模板数据格式不正确')
    }
    
    // 创建示例Excel数据
    const exampleData = data.exampleData || []
    if (exampleData.length === 0) {
      exampleData.push({
        '建筑ID': '01010002',
        '建筑名称': '示例建筑',
        '建筑类型编码': '01',
        '经度': '116.1201',
        '纬度': '39.9401',
        '详细地址': '北京市门头沟区示例街道1号'
      })
    }
    
    // 转换为CSV格式
    const headers = Object.keys(exampleData[0])
    let csvContent = '\uFEFF' + headers.join(',') + '\n' // 添加BOM以支持中文
    
    exampleData.forEach(row => {
      const values = headers.map(header => {
        const value = row[header] || ''
        // 处理包含逗号或引号的值
        return `"${value.toString().replace(/"/g, '""')}"`
      })
      csvContent += values.join(',') + '\n'
    })
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '建筑信息导入模板.csv'
    document.body.appendChild(a)
    a.click()
    // 增加延迟确保下载完成
    setTimeout(() => {
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }, 100)
    
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    // 详细的错误提示
    let errorMsg = '下载模板失败，请稍后再试'
    if (error.message.includes('Failed to fetch')) {
      errorMsg = '网络连接失败，请检查网络后重试'
    } else if (error.message.includes('模板数据格式')) {
      errorMsg = '模板数据格式错误，请联系管理员'
    }
    ElMessage.error(errorMsg)
  }
}

// 加载模板信息
const loadTemplateInfo = async () => {
  try {
    const data = await apiService.getImportTemplate()
    // 延迟设置数据，避免ResizeObserver冲突
    setTimeout(() => {
      templateInfo.value = data
    }, 0) // 0ms延迟将任务放入队列尾部
    templateInfo.value = await apiService.getImportTemplate()
  } catch (error) {
    console.error('加载模板信息失败:', error)
    // 使用默认模板信息
    templateInfo.value = {
      requiredFields: [
        { 
          field: '建筑ID', 
          description: '建筑的唯一标识符',
          aliases: ['id', '建筑编号']
        },
        { 
          field: '建筑名称', 
          description: '建筑的名称',
          aliases: ['名称', 'building_name']
        },
        { 
          field: '建筑类型', 
          description: '建筑类型名称或编码',
          aliases: ['类型', 'building_type']
        }
      ],
      optionalFields: [
        { 
          field: '坐标', 
          description: '建筑的经纬度坐标，格式：经度,纬度',
          aliases: ['coordinates', '位置']
        },
        { 
          field: '乡镇', 
          description: '所属乡镇名称或编码',
          aliases: ['乡镇名称', 'town']
        },
        { 
          field: '详细地址', 
          description: '建筑的详细地址'
        }
      ],
      notes: [
        'ID建议设置为文本格式，避免前导0丢失',
        '坐标格式示例：116.1201,39.9401（经度范围±180，纬度范围±90）',
        '建筑类型支持名称自动转换为编码（如"住宅"自动转换为对应编码）',
        '重复的建筑ID将被自动跳过'
      ],
      exampleData: [
        {
          '建筑ID': '01010001',
          '建筑名称': '行政中心',
          '建筑类型': '公共建筑',
          '坐标': '116.1201,39.9401',
          '乡镇': '城子街道'
        },
        {
          '建筑ID': '01010002',
          '建筑名称': '文化中心',
          '建筑类型': '文化设施',
          '坐标': '116.1302,39.9502',
          '乡镇': '永定镇'
        },
        {
          '建筑ID': '01010003',
          '建筑名称': '体育中心',
          '建筑类型': '体育设施',
          '坐标': '116.1403,39.9603',
          '乡镇': '龙泉镇'
        }
      ]
    }
  }
}

// 初始化
onMounted(() => {
  loadTemplateInfo()
})
</script>

<style scoped>
.file-upload {
  margin-bottom: 20px;
}

.upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.upload-dragger {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-content {
  text-align: center;
}

.upload-icon {
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text p {
  margin: 8px 0;
  color: #606266;
  font-size: 16px;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-hint {
  margin-top: 16px;
}

.upload-hint p {
  margin: 4px 0;
  color: #909399;
  font-size: 12px;
}

.selected-file {
  margin: 16px 0;
}

.file-info {
  display: flex;
  gap: 20px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.upload-progress {
  margin-top: 16px;
}

.import-result {
  margin-top: 20px;
}

.result-alert {
  margin-bottom: 16px;
}

.result-details {
  margin-top: 12px;
}

.result-stats {
  display: flex;
  gap: 40px;
  margin-bottom: 16px;
}

.error-details {
  margin-top: 16px;
}

.error-details h4 {
  margin: 0 0 8px 0;
  color: #f56c6c;
  font-size: 14px;
}

.error-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding: 8px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.error-message {
  color: #606266;
  font-size: 12px;
}

.available-data {
  margin-top: 16px;
  padding: 12px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.available-data h4 {
  margin: 0 0 8px 0;
  color: #409eff;
  font-size: 14px;
}

.data-section {
  margin-bottom: 12px;
}

.data-section:last-child {
  margin-bottom: 0;
}

.data-section strong {
  color: #606266;
  font-size: 12px;
}

.data-tags {
  margin-top: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.data-tag {
  font-size: 10px;
}

.upload-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.template-info {
  margin-top: 20px;
}

:deep(.template-info .el-table) {
  max-height: 300px; /* 固定最大高度 */
  overflow: auto;
}

.template-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.field-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.field-tag {
  cursor: help;
}

@media (max-width: 768px) {
  .result-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .upload-actions {
    flex-direction: column;
  }
  
  .data-tags {
    flex-direction: column;
    align-items: flex-start;
  }

  .file-info {
    flex-direction: column;
    gap: 8px;
  }

  .file-actions {
    justify-content: center;
  }
}
</style>